<template>
    <div>
        <div :id="editorId" :value="value"></div>
    </div>
</template>

<script>
    // import $ from 'jquery'
    export default {
        name: 'TinymceEditor',
        props: {
            value: {
                type: String
            },
            tinymcePath: {
                type: String,
                default: './tinymce-5.1.1/'
            },
            uploadPath: {
                type: String,
                default: '/UEditor/FileUp'
            },
            editorId: {
                type: String,
                required: true
            },
            height: {
                type: Number,
                default: 400
            }
        },
        data() {
            return {
                editor: ''
            }
        },
        mounted() {
            console.log(window.tintymce)
            if(window.tinymce){
                this.tinymceInit(this.editorId)
            }else {
                this.addScriptTag('tinymce.min.js').then(() => {
                    console.log(window.tinymce)
                    //多个编辑器
                    setTimeout(() => {
                    this.tinymceInit(this.editorId)
                    }, 1000);
                })
            }
        },
        beforeDestroy() {
            // 销毁
            window.tinymce.remove(`#${this.editorId}`);
            // window.tinymce.get(this.editorId).destroy();
        },
        methods: {
            async tinymceInit(id) {
                await window.tinymce
                    .init({
                        selector: `#${id}`,
                        // language_url: '/assets/tinymce/lang/zh_CN.js', // 语言包的路径
                        language: 'zh_CN', // 语言
                        //skin_url: '/assets/tinymce-5.1.1/skins/ui/oxide', // skin路径，注意这个，很多网上教程都是skins/lightgray，但是发现其实并没有这个玩意儿
                        height: this.height, // 编辑器高度
                        branding: false, // 是否禁用“Powered by TinyMCE”
                        menubar: true, // 顶部菜单栏显示
                        plugins: 'lists image table wordcount code link hr preview searchreplace',
                        toolbar: 'undo redo |  formatselect | bold italic hr forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image table | code searchreplace link preview | removeformat ',
                        //图片上传函数
                        images_upload_handler: (blobInfo, succFun, failFun) => {
                            let file = blobInfo.blob() // 转化为易于理解的file对象
                            this.uploadFile(file).then((res) => {
                                console.log(res)
                                succFun(res.url)
                            }).catch((e) => {
                                failFun(e)
                            })
                        },
                        //文件上传函数
                        file_picker_callback: (callback, value, meta) => {
                            let input = document.createElement('input')
                            let _this = this
                            input.setAttribute('type', 'file')
                            input.click()
                            input.onchange = function () {
                                let file = this.files[0]
                                _this.uploadFile(file).then((res) => {
                                    callback(res.url, {
                                        text: res.original
                                    })
                                })
                            }
                        },
                        setup: (editor) => {
                            editor.on('init', () => {
                                // console.log(this.value + id)
                                // debugger
                                editor.setContent(this.value)
                            })
                            editor.on('change keyup', () => {
                                // console.log(editor.getContent() + id)
                                const content = editor.getContent();
                                // 更新文本
                                this.$emit('input', content);
                            });
                        }
                    })
            },
            addScriptTag(name) {
                return new Promise((resolve, reject) => {
                    let scriptTag = document.createElement('script')
                    scriptTag.type = 'text/javascript'
                    scriptTag.src = `${this.tinymcePath}${name}`
                    let head = document.getElementsByTagName('head')[0]
                    head.appendChild(scriptTag)
                    scriptTag.addEventListener('load', () => {
                        console.log('引入tinymce.js成功')
                        console.log(`${this.tinymcePath}${name}`)
                        //head.removeChild(scriptTag)
                        resolve()
                    })
                    scriptTag.addEventListener('error', () => {
                        console.log('引入tinymce.js异常')
                        head.removeChild(scriptTag)
                        reject()
                    })
                })
            },
            uploadFile(file) {
                return new Promise((resolve, reject) => {
                    let fileName = file.name,
                        fileSize = file.size,
                        fileType = file.type
                    let formData = new FormData()
                    formData.append('files', file)
                    // $.ajax({
                    //     url: this.uploadPath, //请求的接口地址
                    //     type: 'POST',
                    //     cache: false, //上传文件不需要缓存
                    //     data: formData,
                    //     processData: false, // 不要去处理发送的数据
                    //     contentType: false, // 不要去设置Content-Type请求头
                    //     success: (ret) => {
                    //         if (ret.state == 'SUCCESS') {
                    //             resolve(ret)
                    //         }
                    //     },
                    //     error: (err) => {
                    //         reject(err)
                    //     }
                    // })
                })
            }
        }
    }

</script>
